package com.journal.common.utils.ip;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.journal.common.config.RuoYiConfig;
import com.journal.common.constant.Constants;
import com.journal.common.utils.StringUtils;
import com.journal.common.utils.http.HttpUtils;

/**
 * 获取地址类
 * 
 * @author ruoyi
 */
public class AddressUtils
{
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    // IP地址查询 - 主API
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
    
    // 备用API列表
    private static final String[] BACKUP_IP_APIS = {
        "http://ip-api.com/json/%s?lang=zh-CN&fields=status,country,regionName,city",
        "https://ipapi.co/%s/json/",
        "http://ip.sb/api/geoip/%s"
    };

    // 未知地址
    public static final String UNKNOWN = "XX XX";

    /**
     * 获取IP地址对应的真实地址（原有方法，保持兼容）
     * 
     * @param ip IP地址
     * @return 地址信息
     */
    public static String getRealAddressByIP(String ip)
    {
        // 内网不查询
        if (IpUtils.internalIp(ip))
        {
            return "内网IP";
        }
        if (RuoYiConfig.isAddressEnabled())
        {
            try
            {
                String rspStr = HttpUtils.sendGet(IP_URL, "ip=" + ip + "&json=true", Constants.GBK);
                if (StringUtils.isEmpty(rspStr))
                {
                    log.error("获取地理位置异常 {}", ip);
                    return UNKNOWN;
                }
                JSONObject obj = JSON.parseObject(rspStr);
                String region = obj.getString("pro");
                String city = obj.getString("city");
                return String.format("%s %s", region, city);
            }
            catch (Exception e)
            {
                log.error("获取地理位置异常 {}", ip);
            }
        }
        return UNKNOWN;
    }

    /**
     * 获取IP地址对应的地理位置（优化版，支持多个备用API）
     * 
     * @param ip IP地址
     * @return 地理位置信息
     */
    public static String getLocationByIP(String ip)
    {
        // 内网或本地IP
        if (IpUtils.internalIp(ip) || StringUtils.isEmpty(ip) || 
            "unknown".equalsIgnoreCase(ip) || "127.0.0.1".equals(ip) || 
            "localhost".equals(ip))
        {
            return "本地";
        }

        // 首先尝试使用原有的API（如果启用）
        if (RuoYiConfig.isAddressEnabled())
        {
            try
            {
                String rspStr = HttpUtils.sendGet(IP_URL, "ip=" + ip + "&json=true", Constants.GBK);
                if (StringUtils.isNotEmpty(rspStr))
                {
                    JSONObject obj = JSON.parseObject(rspStr);
                    String region = obj.getString("pro");
                    String city = obj.getString("city");
                    if (StringUtils.isNotEmpty(region) || StringUtils.isNotEmpty(city))
                    {
                        return String.format("%s %s", 
                            StringUtils.isNotEmpty(region) ? region : "", 
                            StringUtils.isNotEmpty(city) ? city : "").trim();
                    }
                }
            }
            catch (Exception e)
            {
                log.debug("主API获取地理位置失败，尝试备用API: {}", e.getMessage());
            }
        }

        // 尝试备用API
        for (String apiUrl : BACKUP_IP_APIS)
        {
            try
            {
                String url = String.format(apiUrl, ip);
                String response = HttpUtils.sendGet(url, null);
                
                if (StringUtils.isNotEmpty(response))
                {
                    JSONObject jsonObject = JSON.parseObject(response);
                    String location = parseLocationFromResponse(jsonObject, apiUrl);
                    if (StringUtils.isNotEmpty(location) && !UNKNOWN.equals(location))
                    {
                        return location;
                    }
                }
            }
            catch (Exception e)
            {
                log.debug("备用API {} 获取地理位置失败: {}", apiUrl, e.getMessage());
                // 继续尝试下一个API
            }
        }

        log.warn("所有IP地理位置API均失败，IP: {}", ip);
        return UNKNOWN;
    }

    /**
     * 从不同API的响应中解析地理位置信息
     * 
     * @param jsonObject JSON响应对象
     * @param apiUrl API地址（用于判断API类型）
     * @return 地理位置信息
     */
    private static String parseLocationFromResponse(JSONObject jsonObject, String apiUrl)
    {
        StringBuilder location = new StringBuilder();

        // ip-api.com 格式
        if (apiUrl.contains("ip-api.com"))
        {
            if ("success".equals(jsonObject.getString("status")))
            {
                String country = jsonObject.getString("country");
                String regionName = jsonObject.getString("regionName");
                String city = jsonObject.getString("city");
                
                if (StringUtils.isNotEmpty(country)) {
                    location.append(country);
                }
                if (StringUtils.isNotEmpty(regionName)) {
                    if (location.length() > 0) location.append(" ");
                    location.append(regionName);
                }
                if (StringUtils.isNotEmpty(city)) {
                    if (location.length() > 0) location.append(" ");
                    location.append(city);
                }
            }
        }
        // ipapi.co 格式
        else if (apiUrl.contains("ipapi.co"))
        {
            if (!jsonObject.containsKey("error"))
            {
                String country = jsonObject.getString("country_name");
                String region = jsonObject.getString("region");
                String city = jsonObject.getString("city");
                
                if (StringUtils.isNotEmpty(country)) {
                    location.append(country);
                }
                if (StringUtils.isNotEmpty(region)) {
                    if (location.length() > 0) location.append(" ");
                    location.append(region);
                }
                if (StringUtils.isNotEmpty(city)) {
                    if (location.length() > 0) location.append(" ");
                    location.append(city);
                }
            }
        }
        // ip.sb 格式
        else if (apiUrl.contains("ip.sb"))
        {
            String country = jsonObject.getString("country");
            String region = jsonObject.getString("region");
            String city = jsonObject.getString("city");
            
            if (StringUtils.isNotEmpty(country)) {
                location.append(country);
            }
            if (StringUtils.isNotEmpty(region)) {
                if (location.length() > 0) location.append(" ");
                location.append(region);
            }
            if (StringUtils.isNotEmpty(city)) {
                if (location.length() > 0) location.append(" ");
                location.append(city);
            }
        }

        return location.length() > 0 ? location.toString() : UNKNOWN;
    }
}
